package com.partsoft.dits.log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.util.Assert;

public class FileLogAttachment extends AbstractLogAttachment implements LogAttachment, Cloneable, Serializable {
	
	private static final long serialVersionUID = -4091751828267288004L;
	
	private File attachFile;

	public File getAttachFile() {
		return attachFile;
	}

	public void setAttachFile(File attachFile) {
		this.attachFile = attachFile;
	}
	
	public InputStream getInputStream() throws IOException {
		Assert.notNull(getAttachFile());
		return FileUtils.openInputStream(getAttachFile());
	}
	
	public void writeAttachment(byte[] bytes) throws IOException {
		Assert.notNull(bytes);
		Assert.notNull(getAttachFile());
		FileUtils.writeByteArrayToFile(getAttachFile(), bytes);
	}
	
	public void writeAttachment(InputStream inputStream) throws IOException {
		Assert.notNull(inputStream);
		Assert.notNull(getAttachFile());
		FileUtils.writeByteArrayToFile(getAttachFile(), IOUtils.toByteArray(inputStream));
	}
	
	public void clearAttachmentFile(){
		Assert.notNull(getAttachFile());
		FileUtils.deleteQuietly(getAttachFile());
	}

	@Override
	public FileLogAttachment clone() {
		return (FileLogAttachment) super.clone();
	}
	
}
